<?php
/*
 * Created on Nov 27, 2010
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 
include_once './configure/ppsdk_include_path.inc';
include_once("customerSession.inc.php");

require_once 'PayPal.php';
require_once 'PayPal/Profile/Handler/Array.php';
require_once 'PayPal/Profile/API.php';
require_once 'paypal-app/SampleLogger.php';
require_once 'paypal-app/PaymentPro.php';
include_once ("paypal-app/PaypalInfo.php");		//-- for payment

include_once("Common.php");
include_once ("Session.php");					//-- Session
include_once ("Password.php");					//-- Password

include_once ("CustomerDao.php");				//-- for payment
include_once ("AddressBookDao.php");			//-- for payment

include_once ("orders/OrdersInfo.php");				//-- for payment
include_once ("orders/OrdersAccount.php");			//-- for payment

include_once("orders/Cart.php");					//--> Cart
include_once("orders/CartProduct.php");				//--> Cart
include_once("orders/CartProductAttribute.php");	//--> Cart

require_once('includeHttps.php');

session_start();

$common 			= new Common();
$objPassword 		= new Password();
$objCustomerDao 	= new CustomerDao();
$objOrdersInfo		= new OrdersInfo();
$objPaypalInfo		= new PaypalInfo();

$objSession			= new Session(DB_TAG_SYSTEM, SESSION_TABLE_NAME);	//-- session
$payment 			= new PaymentPro();
$logger 			= new SampleLogger('expressCheckout.php', PEAR_LOG_DEBUG);

$customerid = 0;

/*----- check session -----*/
if($objSession->exist()) {
	$customerid = $objSession->getUserID();
}

if($_SESSION['cart']){
	$objCart = unserialize($_SESSION['cart']);
}else{
	$location = HOME_URL;
	
	header("Location: $location");
	exit;
}
		
$profile = $payment->sessionStart3Tokens();
	
$objPaypalInfo->setAPIProfile($profile);

if(isset($_SESSION['customerInfo'])){
	$objCustomerDao = unserialize($_SESSION['customerInfo']);
}

if(isset($_SESSION['ordersInfo'])){
	$objOrdersInfo = unserialize($_SESSION['ordersInfo']);
}


$APIprofile = $objPaypalInfo->getAPIProfile();
if(!isset($APIprofile) || empty($APIprofile)){
	$location = 'checkout.php';
    
    header("Location: $location");
}

$token = $_REQUEST['token'];
if(! isset($token)) {
	$paymentAmount = $objOrdersInfo->getAccount()->getAllTotal();

   	$currencyCodeType  	= 'USD';
   	$paymentType		= 'Sale';
	
	$returnURL = HOME_URL_HTTPS . '/expressCheckout.php?paymentAmount='.$paymentAmount.'&currencyCodeType='.$currencyCodeType.'&paymentType='.$paymentType;
	
   	$cancelURL = HOME_URL . '/viewCart.php';
 
//   	$cancelURL = str_replace('expressCheckout', 'expressCheckoutCancel', $returnURL);

   	$ec_request =& PayPal::getType('SetExpressCheckoutRequestType');

   	//Setting up URL information.
   	$ec_details =& PayPal::getType('SetExpressCheckoutRequestDetailsType');
   	$ec_details->setReturnURL($returnURL);
   	$ec_details->setCancelURL($cancelURL);
   	$ec_details->setCallbackTimeout('20');
//   $ec_details->setBuyerEmail($_POST['buyersemail']);
   	$ec_details->setPaymentAction($paymentType);
	
   	//Setting up OrderTotal.
   	$amt_type =& PayPal::getType('BasicAmountType');
   	$amt_type->setattr('currencyID', $currencyCodeType);
   	$amt_type->setval($paymentAmount, 'iso-8859-1');
   	$ec_details->setOrderTotal($amt_type);

 	
// 	//Addition of Product Details.	
//	$paymentDetailsType = &PayPal::getType('PaymentDetailsType');
//	
//	$arrItems = array();
//	
// 	$arrProducts = $objCart->getProductList();
// 	$len = count($arrProducts);
// 	for($i = 0; $i < $len; $i++){
// 		$paymentDetailsItem = &PayPal::getType('PaymentDetailsItemType');
//		$paymentDetailsItem->setName($arrProducts[$i]->getName());
//		$paymentDetailsItem->setQuantity($arrProducts[$i]->getQuantity(), 'iso-8859-1');
//		$paymentDetailsItem->setAmount($arrProducts[$i]->getFinalPrice() / 100, 'iso-8859-1');
// 	
// 		
// 		$item = 'PaymentDetailsItem' . sprintf("%02d", $i);
// 		$arrItems[$item] = $paymentDetailsItem;
// 	}
// 	
//	$paymentDetailsType->setPaymentDetailsItem($arrItems);
// 	
// 	//Setting up OrderTotal on PaymentDetails.
//	$itemTotal_type =& PayPal::getType('BasicAmountType');
//   	$itemTotal_type->setattr('currencyID', $currencyCodeType);
//   	$itemTotal_type->setval($objOrdersInfo->getAccount()->getProductTotal(), 'iso-8859-1');
//   	$paymentDetailsType->setItemTotal($itemTotal_type);
// 	
// 	
// 	//Setting up Tax details
//	$taxTotal_type =& PayPal::getType('BasicAmountType');
//   	$taxTotal_type->setattr('currencyID', $currencyCodeType);
//   	$taxTotal_type->setval($objOrdersInfo->getAccount()->getTaxTotal(), 'iso-8859-1');
//	$paymentDetailsType->setTaxTotal($taxTotal_type);
// 	
// 	//Setting up Shipping Total on PaymentDetails.
//	$shipamt_type =  &PayPal::getType('BasicAmountType');
//   	$shipamt_type->setattr('currencyID', $currencyCodeType);
//   	$shipamt_type->setval($objOrdersInfo->getAccount()->getShippingTotal(), 'iso-8859-1');
//	$paymentDetailsType->setShippingTotal($shipamt_type);
// 	
// 	$sDiscount = 0 - round($objCart->getSaveOff() / 100, 2);
// 	
// 	//Setting up the Shipping discount
//	$sDiscount_type =& PayPal::getType('BasicAmountType');
//   	$sDiscount_type->setattr('currencyID', $currencyCodeType);
//   	$sDiscount_type->setval($sDiscount, 'iso-8859-1');
//	$paymentDetailsType->setShippingDiscount($sDiscount_type);
// 	
// 	
// 	$ec_details->setPaymentDetails($paymentDetailsType);
// 	
   	$ec_request->setSetExpressCheckoutRequestDetails($ec_details);

   	/*
   	 * Creating CallerServices object
   	 */
	$caller =& PayPal::getCallerServices($objPaypalInfo->getAPIProfile());
	$caller->USE_ARRAYKEY_AS_TAGNAME = true;
	$caller->SUPRESS_OUTTAG_FOR_ARRAY = true;
	$caller->OUTTAG_SUPRESS_ELEMENTS = array('PaymentDetailsItem','FlatRateShippingOptions');
   
   // Execute SOAP request
   $response = $caller->SetExpressCheckout($ec_request);
   
   $logger->_log('SetExpressCheckout response: '. print_r($response,true));

   $ack = $response->getAck();

   $logger->_log('Ack='.$ack);

   switch($ack) {
      case ACK_SUCCESS:
      case ACK_SUCCESS_WITH_WARNING:
         // Good to break out;

         // Redirect to paypal.com here
         $token 	= $response->getToken();
         $payPalURL = $payment->getPaypalURL().$token;
         
         // $display=$payPalURL;
         $logger->_log('Redirect to PayPal for payment: '. $payPalURL);
         
         header("Location: ".$payPalURL);
         exit;

      default:
         $_SESSION['response'] =& $response;
         $logger->_log('SetExpressCheckout failed: ' . print_r($response, true));
         
		$location = HOME_URL . "/lib/paypal-app/ApiError.php";
        header("Location: $location");
   }
} else {
   // We have a TOKEN from paypal
   // GetExpressCheckoutDetails handling here
	$paymentType		= $_REQUEST['paymentType'];
	$token 				= $_REQUEST['token'];
	$paymentAmount		= $_REQUEST['paymentAmount'];
	$currencyCodeType	= $_REQUEST['currencyCodeType'];

    $objPaypalInfo->setToken($token);
    $objPaypalInfo->setPaymentType($paymentType);
    $objPaypalInfo->setPaymentAmount($paymentAmount);
    $objPaypalInfo->setCurrencyCodeType($currencyCodeType);
    
    $objPaypalInfo->setPaymentMethod('PayPal');

   $ec_request =& PayPal::getType('GetExpressCheckoutDetailsRequestType');
   $ec_request->setToken($token);

   $caller =& PayPal::getCallerServices($objPaypalInfo->getAPIProfile());

   // Execute SOAP request
   $response = $caller->GetExpressCheckoutDetails($ec_request);
   
   $logger->_log('GetExpressCheckoutDetails response: '. print_r($response,true));

   $ack = $response->getAck();

   $logger->_log('Ack='.$ack);

   switch($ack) {
      case ACK_SUCCESS:
      case ACK_SUCCESS_WITH_WARNING:
         // Continue on based on the require below...
         break;

      default:
         $_SESSION['response'] =& $response;
         $logger->_log('SetExpressCheckout failed: ' . print_r($response, true));
         
		$location = HOME_URL . "/lib/paypal-app/ApiError.php";
        header("Location: $location");
   }

	// process shipping
	$details = $response->getGetExpressCheckoutDetailsResponseDetails();

    // This is the clients payer information
	$payer_info = $details->getPayerInfo();

    // get the payer_id from the clients payer info
	$payer_id 		= $payer_info->getPayerID();
    $fullname 		= $payer_info->getPayerName();
    $address_info 	= $payer_info->getAddress();
    $phone 			= $details->getContactPhone();
    
    $objPaypalInfo->setPayerid($payer_id);
    
	$country = $common->getRow(DB_TAG_SYSTEM, 'SELECT id, name, addrFormatID FROM countries WHERE code2 ="' . $address_info->Country . '"');
	if(count($country) > 0){
		$country_id 		= $country['id'];
        $country_name 		= $country['name'];
        $address_format_id 	= $country['addrFormatID'];
	}else{
		$country_id 		= '223';
        $country_name 		= 'United States';
        $address_format_id 	= '2'; // 2 is the American format
	}

	$state_id = $common->getColumn(DB_TAG_SYSTEM, 'SELECT id FROM zones WHERE code = \'' . $address_info->StateOrProvince . "' AND countryID = $country_id");
   	// see if we found a record
    if (empty($state_id)) {
        $state_id = 0; // default
    }
  
  	$objAddressBookDao = new AddressBookDao();
  	
  	$objAddressBookDao->setFirstName($fullname->FirstName);
	$objAddressBookDao->setLastName($fullname->LastName);
	$objAddressBookDao->setStreet($address_info->Street1);
	$objAddressBookDao->setSuburb($address_info->Street2);
	$objAddressBookDao->setCity($address_info->CityName);
	$objAddressBookDao->setZoneid($state_id);
	$objAddressBookDao->setState($address_info->StateOrProvince);
	$objAddressBookDao->setZipcode($address_info->PostalCode);
	$objAddressBookDao->setCountryid($country_id);
	$objAddressBookDao->setCountry($country_name);
    

  	// not logined in.
  	if(empty($customerid)){
  		$customer = $common->getRow(DB_TAG_SYSTEM, 'SELECT id, paypal_ec, lastname FROM customers WHERE email ="' . $payer_info->Payer . '"');
	   	// see if we found a record

	    if (count($customer) > 0) {
	    	if ($customer['paypal_ec'] == '1') {
	    		
	    		$sql = "DELETE FROM address_book WHERE customerid = " . $customer['id'];
				$common->update(DB_TAG_SYSTEM, $sql);
	    		
	    		$sql = "DELETE FROM customers WHERE id = " . $customer['id'];
				$common->update(DB_TAG_SYSTEM, $sql);
				
				$customer = array();
	    	}else{
	    		$customerid 		= $customer['id'];
	    	}
	    }
	    
	    if (count($customer) < 1) {
	        $salt = '46z3haZzegmn676PA3rUw2vrkhcLEn2p1c6gf7vp2ny4u3qqfqBh5j6kDhuLmyv9xf';
            srand((double)microtime() * 1000000);
            $password = '';
            for ($x = 0; $x < 7; $x++) {
                $num = rand() % 33;
                $tmp = substr($salt, $num, 1);
                $password = $password . $tmp;
            }
            
            $objCustomerDao->setFirstName($fullname->FirstName);
            $objCustomerDao->setLastName($fullname->LastName);
            $objCustomerDao->setEmail($payer_info->Payer);
            $objCustomerDao->setTelephone($address_info->Phone);
            $objCustomerDao->setFax('');
            $objCustomerDao->setNewsletter(0);
            $objCustomerDao->setPaypalEC(1);
            $objCustomerDao->setPaypalPayerid($payer_id);
            $objCustomerDao->setPassword($objPassword->encrypt($password));
            $objCustomerDao->setCreatedTime('UTC_TIMESTAMP()');
            $objCustomerDao->setModifiedTime('UTC_TIMESTAMP()');
            $objCustomerDao->setCountryid($country_id);
            $objCustomerDao->setNewsletter('unsubscribed');
            $objCustomerDao->setAutoRegister(1);
             
            // insert the data
        	$customerid = $common->insertUpdate(DB_TAG_SYSTEM, 'customers', $objCustomerDao->getArray());
			
			$objCustomerDao->setID($customerid);
			
        	$objAddressBookDao->setCustomerid($customerid);
        	
           // insert the data
            $addressid = $common->insertUpdate(DB_TAG_SYSTEM, 'address_book', $objAddressBookDao->getArray());
			
			$objAddressBookDao->setID($addressid);
			$objCustomerDao->setAddressid($addressid);
			
            $sql = "UPDATE customers SET modifiedTime = UTC_TIMESTAMP(), default_address_id = '$addressid' WHERE id = $customerid";
			$common->update(DB_TAG_SYSTEM, $sql);
	    }
	    
	    $arrdata = array();
		$arrdata['lastname']	= $objCustomerDao->getLastName();		//--> add login name to session
	
		if(!is_array($objSession->start($customerid, $arrdata))){
			$location = HOME_URL . "/lib/paypal-app/ApiError.php";
			
			header("Location: $location");
			
			exit;
		}
		
  	}else{
  		$customer = $common->getRow(DB_TAG_SYSTEM, "SELECT * FROM customers WHERE id =$customerid");
  		
  		$objCustomerDao->setID($customerid);
  		$objCustomerDao->setFirstName($customer['firstname']);
        $objCustomerDao->setLastName($customer['lastname']);
        $objCustomerDao->setEmail($customer['email']);
        $objCustomerDao->setTelephone($customer['telephone']);
        $objCustomerDao->setFax($customer['fax']);
        $objCustomerDao->setNewsletter($customer['newsletter']);
        $objCustomerDao->setPaypalEC($customer['paypal_ec']);
        $objCustomerDao->setPaypalPayerid($customer['paypal_payerid']);
        $objCustomerDao->setPassword($customer['password']);
        $objCustomerDao->setCreatedTime('UTC_TIMESTAMP()');
        $objCustomerDao->setModifiedTime('UTC_TIMESTAMP()');
        $objCustomerDao->setCountryid($customer['countryid']);
        $objCustomerDao->setAddressid($customer['default_address_id']);
  	}

	$objOrdersInfo->setCustomerAddress($objAddressBookDao);
	$objOrdersInfo->setBillingAddress($objAddressBookDao);
	
	$objOrdersInfo->setPaymentMethod(OrdersInfo::EXPRESS_CHECKOUT);
	
	$_SESSION['paypalInfo'] 		= serialize($objPaypalInfo);
	$_SESSION['customerInfo'] 		= serialize($objCustomerDao);
	$_SESSION['ordersInfo'] 		= serialize($objOrdersInfo);

	$location = 'checkoutFinish.php';
	
	header("Location: $location");
}

?>
